<template>
  <view class="avatarsList flex flex-column align-center bg_F5F5F5 pageHeight">
    <s-header-title ref="headerTitle" isDisplayBack title="头像编辑" is-fixed background="#FFFFFF"
                  @getPageHeight="getPageHeight"></s-header-title>
    <view :style="{height:`${page.headerHeight}px`}"></view>
    <view class="list mt_65">
      <view v-for="(item,index) in page.avatarsList" :key="index" class="flex align-center justify-center"
            @click="page.selectAvatarIndex = index">
        <image-avater :width="120" :height="120" :src="`${nc_image}${item.avatar}`" :border-width="12" isOrder
                      :border-color="page.selectAvatarIndex == index ? '#FF4206' : '#f5f5f5'"></image-avater>
      </view>
    </view>
    <view class="upload flex align-center justify-center mt_48" @click="uploadAvatar" style="position: relative;">
      <text class="upload_text">手动上传</text>
      <!--      <image :src="`${IMG_URL}/index/vipopen.png`"-->
      <!--             style="width: 95rpx;height: 29rpx;position:absolute;top: -14rpx;right: 0;"></image>-->
    </view>
    <view class="confirm flex align-center justify-center mt_48" @click="confirmAvatar">
      <text class="confirm_text">确定</text>
    </view>

    <uni-popup ref="uploadPopup" type="bottom">
      <view class="uploadPopup">
        <view class="uploadPopup_top row items-center justify-between">
          <view class="uploadPopup_top_text ml-44">
            选择类型
          </view>
          <image @click.stop="closePopup" class="mr-44" :src="`${IMG_URL}close_family_upload.png`"></image>
        </view>
        <view class="uploadPopup_content flex flex-column align-center justify-center w-full">
          <view class="lists allRowCenter" :style="{
                marginTop: index == 0 ? '0rpx' : '56rpx'
              }" v-for="(item,index) in page.uploadMode" :key="index" @click.stop="selectMode(item.mode)">
            <image :src="`${IMG_URL}${item.icon}`"></image>
            <view class="text ml-15">{{ item.name }}</view>
            <image :src="`${IMG_URL}/index/vipopen.png`"
                   style="width: 95rpx;height: 29rpx;position:absolute;top: -14rpx;right: 0;"></image>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
  import HeaderTitle from '@/pages/familyPage/components/headerTitle.vue';
  import ImageAvater from '@/sheep/components/s-avatar/s-avatar.vue';
  import { computed, reactive, ref } from 'vue';
  import sheep from '@/sheep';
  import { onLoad } from '@dcloudio/uni-app';
  import { showAuthModal } from '@/sheep/hooks/useModal';
  // #ifdef APP-PLUS
  import permision from '@/uni_modules/all-speech/js_sdk/wa-permission/permission';
  // #endif

  const page = reactive({
    avatarsList: [],
    headerHeight: 0,
    options: {},
    selectAvatarIndex: -1,
    uploadMode: [
      { name: '相册上传', icon: '/index/upload_icon_photo.png', mode: 'album' },
      { name: '拍照上传', icon: '/index/upload_icon_ablum.png', mode: 'camera' },
    ],
  });
  const vipDisposition = reactive({
    isShow: false,
    goodDetails: {},
  });

  const IMG_URL = computed(() => sheep.$store('AI').sq_image_path);
  const nc_image = computed(() => sheep.$store('AI').nc_image);
  const userInfo = computed(() => sheep.$store('user').userInfo);

  onLoad(async (opotins) => {
    const { data } = await sheep.$api.goods.ids({ ids: '10' });
    vipDisposition.goodDetails = data[0];
    page.options = opotins;
    console.log(page.options);
    await getAvatarsList();
  });

  function getPageHeight(number) {
    page.headerHeight = number;
  }

  // 获取系统头像
  const getAvatarsList = async () => {
    const res = await sheep.$api.family.getDefaultAvatar({ type: page.options.sex });
    page.avatarsList = res.data;
  };
  const uploadPopup = ref();
  const CAMERA_PERMISSION_DENIED_TITLE = '开启相机权限';
  const CAMERA_PERMISSION_DENIED_CONTENT = '你还没有开启相机权限，无法使用拾亲扫描功能、拍照或录制视频功能';
  const PHOTO_PERMISSION_DENIED_TITLE = '开启相册权限';
  const PHOTO_PERMISSION_DENIED_CONTENT = '你还没有开启相册权限，无法使用设置头像功能、发布圈子或相册功能';
  const PHOTOW_PERMISSION_DENIED_TITLE = '开启相册权限';
  const PHOTOW_PERMISSION_DENIED_CONTENT = '你还没有开启相册权限，无法使用设置头像功能、发布圈子或相册功能';

  async function uploadAvatar() {
    // #ifdef APP-PLUS
    if (sheep.$platform.device.platform.toLowerCase() === 'ios') {
      uni.chooseImage({
        count: 1,
        success: async res => {
          uni.setStorageSync('ancestralHallSrc', res.tempFilePaths[0]);
          sheep.$router.go('/pages/commission/setAvatar', {
            id: page.options.member_id,
            flag: 1,
            is_genealoy: page.options.is_family == 1 ? 0 : 1,
          });
        },
      });
    } else {
      let res = plus.navigator.checkPermission('android.permission.CAMERA');
      let res1 = plus.navigator.checkPermission('android.permission.READ_EXTERNAL_STORAGE');
      let res2 = plus.navigator.checkPermission('android.permission.WRITE_EXTERNAL_STORAGE');
      if ((res == 'authorized') && (res1 == 'authorized') && (res2 == 'authorized')) {
        if (sheep.$platform.device.platform.toLowerCase() === 'ios' || sheep.$platform.device.platform.toLowerCase() === 'android') {
          if (await checkCameraPermission(sheep.$platform.device.platform)) {
            await handleScanAndChooseImage();
          }
        }
      } else {
        if (res != 'authorized' || res1 != 'authorized' || res2 != 'authorized') {
          uni.showModal({
            title: '开启相册和相机权限',
            content: '你还没有开启相册和相机权限，无法使用拾亲扫描功能、拍照或录制视频功能、设置头像发布圈子等功能',
            success: async (res) => {
              if (res.confirm) {
                if (sheep.$platform.device.platform.toLowerCase() === 'ios' || sheep.$platform.device.platform.toLowerCase() === 'android') {
                  if (await checkCameraPermission(sheep.$platform.device.platform)) {
                    await handleScanAndChooseImage();
                  }
                }
              }
            },
          });
        }
      }
    }

    // #endif
    // #ifndef APP-PLUS
    uni.chooseImage({
      count: 1,
      success: async res => {
        uni.setStorageSync('ancestralHallSrc', res.tempFilePaths[0]);
        sheep.$router.go('/pages/commission/setAvatar', {
          id: page.options.member_id,
          flag: 1,
          is_genealoy: page.options.is_family == 1 ? 0 : 1,
        });
      },
    });
    // #endif
  }


  async function checkCameraPermission(platform) {
    try {
      let limitsOfAuthority;
      if (platform.toLowerCase() === 'ios') {
        limitsOfAuthority = await permision.judgeIosPermission('camera');
      } else {
        limitsOfAuthority = await permision.requestAndroidPermission('android.permission.CAMERA');
      }

      if (limitsOfAuthority !== 1) {
        uni.showModal({
          title: CAMERA_PERMISSION_DENIED_TITLE,
          content: CAMERA_PERMISSION_DENIED_CONTENT,
          success: async (res) => {
            if (res.confirm) {
              permision.gotoAppPermissionSetting();
            }
          },
        });
        return false;
      }
      let photoAlbumWrite;
      if (platform.toLowerCase() === 'ios') {
        photoAlbumWrite = await permision.judgeIosPermission('photoLibrary');
      } else {
        photoAlbumWrite = await permision.requestAndroidPermission('android.permission.READ_EXTERNAL_STORAGE');
      }

      if (photoAlbumWrite !== 1) {
        uni.showModal({
          title: PHOTO_PERMISSION_DENIED_TITLE,
          content: PHOTO_PERMISSION_DENIED_CONTENT,
          success: async (res) => {
            if (res.confirm) {
              permision.gotoAppPermissionSetting();
            }
          },
        });
        return false;
      }

      let photoAlbumRead;
      if (platform.toLowerCase() === 'ios') {
        photoAlbumRead = await permision.judgeIosPermission('photoLibrary');
      } else {
        photoAlbumRead = await permision.requestAndroidPermission('android.permission.WRITE_EXTERNAL_STORAGE');
      }

      if (photoAlbumRead !== 1) {
        uni.showModal({
          title: PHOTOW_PERMISSION_DENIED_TITLE,
          content: PHOTOW_PERMISSION_DENIED_CONTENT,
          success: async (res) => {
            if (res.confirm) {
              permision.gotoAppPermissionSetting();
            }
          },
        });
        return false;
      }

      return true;
    } catch (error) {
      console.error('权限检查失败:', error);
      uni.showToast({ title: '权限检查失败，请稍后再试', icon: 'none' });
      return false;
    }
  }

  async function handleScanAndChooseImage() {
    try {
      uni.chooseImage({
        count: 1,
        success: async res => {
          uni.setStorageSync('ancestralHallSrc', res.tempFilePaths[0]);
          sheep.$router.go('/pages/commission/setAvatar', {
            id: page.options.member_id,
            flag: 1,
            is_genealoy: page.options.is_family == 1 ? 0 : 1,
          });
        },
      });
    } catch (error) {

    }
  }

  async function confirmAvatar() {
    if (page.selectAvatarIndex == -1) {
      uni.showToast({
        title: '请选择头像',
        icon: 'none',
      });
      return;
    }
    console.log(page.options);
    if (page.options.flag != 1) {
      const { code } = await sheep.$api.family.updateFamilyMemberInfo({
        member_id: page.options.member_id,
        avatar: page.avatarsList[page.selectAvatarIndex].avatar,
      });
      uni.$emit('signature');
      uni.navigateBack();
    } else {
      const { code } = await sheep.$api.genealogy.updateMemberInfo({
        id: page.options.member_id,
        head: nc_image.value + page.avatarsList[page.selectAvatarIndex].avatar,
      });
      uni.$emit('signature');
      uni.navigateBack();
    }
  }
</script>


<style scoped lang="scss">
  .avatarsList {
    width: 750rpx;
    min-height: 100vh;
    background: #F5F5F5;
    overflow: hidden;

    .list {
      width: 702rpx;
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      grid-row-gap: 36rpx;
    }

    .upload {
      width: 362rpx;
      height: 80rpx;
      border-radius: 41rpx 41rpx 41rpx 41rpx;
      border: 2rpx solid #FF4206;

      .upload_text {
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 30rpx;
        color: #FF4206;
      }
    }

    .confirm {
      width: 362rpx;
      height: 80rpx;
      background: #FF4206;
      border-radius: 41rpx 41rpx 41rpx 41rpx;

      .confirm_text {
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 30rpx;
        color: #FFFFFF;
      }
    }
  }

  .uploadPopup {
    width: 750rpx;
    height: 546rpx;
    background: #FFFFFF;
    border-radius: 20rpx 20rpx 0rpx 0rpx;

    .uploadPopup_top {
      width: 750rpx;
      height: 105rpx;
      background: url($uni-bg-url + "/upload_avatar_popup.png") no-repeat;
      background-size: 750rpx 105rpx;

      .uploadPopup_top_text {
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 500;
        font-size: 48rpx;
        color: #000000;
      }

      image {
        width: 32rpx;
        height: 32rpx;
      }
    }

    .uploadPopup_content {
      height: calc(546rpx - 105rpx);

      .lists {
        width: 470rpx;
        height: 100rpx;
        background: #F8F8F8;
        border-radius: 8rpx 8rpx 8rpx 8rpx;
        border: 2rpx solid #E5E5E5;
        position: relative;

        image {
          width: 37rpx;
          height: 31rpx;
        }
      }
    }
  }
</style>
